package rs.etf.mips.crossroad.ui;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.JLabel;

public class CustomJLabel extends JLabel {

	private BufferedImage bufferedImage;
	private URL imageURL;

	private int inertia;
	private int columns;
	private int rows;
	private int currentImage;

	public CustomJLabel(URL imageURL, int rows, int columns) {
		super();
		this.imageURL = imageURL;
		this.columns = columns <= 0 ? 1 : columns;
		this.rows = rows <= 0 ? 1 : rows;
		this.currentImage = 0;
		this.bufferedImage = null;
		inertia = 0;
	}

	private Image getScaledImage() {
		if (bufferedImage == null) {
			if (imageURL != null) {
				try {
					bufferedImage = ImageIO.read(imageURL);
				} catch (IOException ex) {
					return null;
				}
			} else {
				return null;
			}
		}
		int posX = bufferedImage.getWidth() * (this.currentImage % (this.columns - 1))
				/ this.columns;
		int posY = bufferedImage.getHeight() * (this.currentImage % (this.rows - 1))
				/ this.rows;
		BufferedImage subImage = bufferedImage.getSubimage(posX, posY,
				bufferedImage.getWidth()/this.columns, bufferedImage.getHeight()/this.rows);
		return subImage.getScaledInstance(this.getWidth(), this.getHeight(),
				Image.SCALE_SMOOTH);
	}

	void setImage(URL imageUrl, int columns, int rows) {
		if (this.imageURL != imageUrl) {
			this.imageURL = imageUrl;
			bufferedImage = null;
			currentImage = 0;
			this.columns = columns <= 0 ? 1 : columns;
			this.rows = rows <= 0 ? 1 : rows;

		}
	}

	public void nextImage() {
//		inertia++;
//		if(inertia<2)return;
//		inertia = 0;
		currentImage = (currentImage + 1) % (rows * columns);
		repaint();
	}

	@Override
	protected void paintComponent(Graphics arg0) {
		this.setIcon(new javax.swing.ImageIcon(this.getScaledImage()));
		super.paintComponent(arg0);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = -2076234388633034915L;

}
